<?php
namespace app\admin\controller;
use app\common\model\GoodsCategories;
use app\common\model\GoodsBrand;
use app\common\model\Goods;
use app\common\model\Room;
use think\Validate;
use think\Db;
use think\Session;

class GoodsController extends BaseController
{
    //商品列表页面
    public function lists()
    { 
        return view();
    }
    //库存管理页面
    public function stock()
    { 
        return view();
    }
    public function update($id)
    { 
        $data = $this->request->post();
        // 记录谁入库
        if(isset($data['is_stock']) && $data['is_stock'] == 1){
            $account_id = Session::get('uid');
            $data['stock_acct_id'] = $account_id;
        }
        $res = Goods::where('id',$id)->update($data);
        if($res){
            $this->success('操作成功','',$data);
        }else{
            $this->error('操作失败','',$data);
        }
        
    }
    public function getList()
    {
        $where = array_filter(input('post.'));
        if(!empty($where['brand_name'])){
            $where['brand_id'] = Db::name('goods_brand')->where('name', $where['brand_name'])->value('id');
            unset($where['brand_name']);
        }
        if(!empty($where['cate_name'])){
            $where['cate_id'] = Db::name('goods_categories')->where('name', $where['cate_name'])->value('id');
            unset($where['cate_name']);
        }
        if(!empty($where['acct_name'])){
            $where['acct_id'] = Db::name('Account')->where('true_name', $where['acct_name'])->value('id');
            unset($where['acct_name']);
        }

        $page = max(input('get.page',0),1);
        $page_size = 10;

        $total = Goods::where($where)->count();
        $goods = Goods::with('brandInfo,cateInfo,acctInfo,items')->where($where)->order('add_time desc')->page($page,$page_size)->select();

        $rows = []; //返回的数据
        $cate_types = GoodsCategories::$types;
        $units = GoodsCategories::$units;
        foreach ($goods as $key => $item) {
            $info['id'] = $item['id'];
            $info['goods_pic'] = config('upload_path') . $item['picture'];
            $info['pic_tmb'] = $this->getThumb($info['goods_pic']);
            $info['brand'] = $item['brand_info']['name'];
            $info['cate_type'] = $cate_types[$item['cate_info']['type']];
            $info['cate_name'] = $item['cate_info']['name'];
            $info['description'] = $item['description'];
            $info['size_set'] = Goods::$size_sets[$item['size_set']];
            $info['goods_unit'] = $units[$item['cate_info']['unit']];
            $info['acct_name'] = $item['acct_info']['true_name'];
            $info['add_time'] = date('Y-m-d H:i',$item['add_time']);
            $info['item_count'] = count($item['items']);
            $info['can_edit'] = time() - $item['add_time'] > 7*24*60*60 ? false: true;
            $info['stock'] = $item['stock'];
            $info['is_stock'] = $item['is_stock'];
            $info['goods_price'] = $item['goods_price'];
            $info['stock_acct_name'] = $item['stock_acct_id'] ? Db::name('account')->where('id',$item['stock_acct_id'])->value('true_name') : '';
            $info['goods_stall_id'] = $item['goods_stall_id'];
            $info['goods_name'] = $item['name'];
            $rows[] = $info;
        }
        $data = [
            'rows'      => $rows,
            'total_page'=> ceil($total/$page_size),
            'page_size' => $page_size,
            'page'      => $page
        ];
        $this->success('成功','',$data);
    }
    public function getWithRoomList()
    {
        $where = array_filter(input('post.'));
        if(!empty($where['brand_name'])){
            $where['brand_id'] = Db::name('goods_brand')->where('name', $where['brand_name'])->value('id');
            unset($where['brand_name']);
        }
        if(!empty($where['cate_name'])){
            $where['cate_id'] = Db::name('goods_categories')->where('name', $where['cate_name'])->value('id');
            unset($where['cate_name']);
        }
        if(!empty($where['acct_name'])){
            $where['acct_id'] = Db::name('Account')->where('true_name', $where['acct_name'])->value('id');
            unset($where['acct_name']);
        }
        // 查询有入库的商品
        $goodsIds = Db::name('Room')->column('goods');
        $where['id'] = ['in',$goodsIds];

        $page = max(input('get.page',0),1);
        $page_size = 10;
        

        // ================
        $total = Room::where([])->count();
        $goods_ids = Goods::with('brandInfo,cateInfo,acctInfo,items,room')->where($where)->order('add_time desc')->column('id');
        $room = Room::with(['goodsinfo' => ['brandInfo','cateInfo','acctInfo','items']])->where('goods','in',$goods_ids)->page($page,$page_size)->select();
        

        $rows = []; //返回的数据
        $cate_types = GoodsCategories::$types;
        $units = GoodsCategories::$units;
        foreach ($room as $key => $res) {
            $item = $res['goodsinfo'];
            $info['id'] = $res['id'];
            $info['goods'] = $item['id'];
            $info['goods_pic'] = config('upload_path') . $item['picture'];
            $info['pic_tmb'] = $this->getThumb($info['goods_pic']);
            $info['brand'] = $item['brand_info']['name'];
            $info['cate_type'] = $cate_types[$item['cate_info']['type']];
            $info['cate_name'] = $item['cate_info']['name'];
            $info['description'] = $item['description'];
            $info['size_set'] = Goods::$size_sets[$item['size_set']];
            $info['goods_unit'] = $units[$item['cate_info']['unit']];
            $info['acct_name'] = $item['acct_info']['true_name'];
            $info['add_time'] = date('Y-m-d H:i',$item['add_time']);
            $info['item_count'] = count($item['items']);
            $info['can_edit'] = time() - $item['add_time'] > 2*24*60*60 ? false: true;
            $info['stock'] = $item['stock'];
            $info['is_stock'] = $item['is_stock'];
            $info['goods_price'] = $item['goods_price'];
            $info['stock_acct_name'] = $item['stock_acct_id'] ? Db::name('account')->where('id',$item['stock_acct_id'])->value('true_name') : '';
            $info['goods_stall_id'] = $item['goods_stall_id'];
            $info['room'] = [''];
            unset($res['goodsinfo']);
            $info['room'] = $res;
            $info['goods_name'] = $item['name'];
            $rows[] = $info;
            
        }
        $data = [
            'rows'      => $rows,
            'total_page'=> ceil($total/$page_size),
            'page_size' => $page_size,
            'page'      => $page
        ];
        $this->success('成功','',$data);


        // $total = Goods::where($where)->count();
        // $goods = Goods::with('brandInfo,cateInfo,acctInfo,items,room')->where($where)->order('add_time desc')->page($page,$page_size)->select();

        // $rows = []; //返回的数据
        // $cate_types = GoodsCategories::$types;
        // $units = GoodsCategories::$units;
        // foreach ($goods as $key => $item) {
        //     $info['id'] = $item['id'];
        //     $info['goods_pic'] = config('upload_path') . $item['picture'];
        //     $info['pic_tmb'] = $this->getThumb($info['goods_pic']);
        //     $info['brand'] = $item['brand_info']['name'];
        //     $info['cate_type'] = $cate_types[$item['cate_info']['type']];
        //     $info['cate_name'] = $item['cate_info']['name'];
        //     $info['description'] = $item['description'];
        //     $info['size_set'] = Goods::$size_sets[$item['size_set']];
        //     $info['goods_unit'] = $units[$item['cate_info']['unit']];
        //     $info['acct_name'] = $item['acct_info']['true_name'];
        //     $info['add_time'] = date('Y-m-d H:i',$item['add_time']);
        //     $info['item_count'] = count($item['items']);
        //     $info['can_edit'] = time() - $item['add_time'] > 2*24*60*60 ? false: true;
        //     $info['stock'] = $item['stock'];
        //     $info['is_stock'] = $item['is_stock'];
        //     $info['goods_price'] = $item['goods_price'];
        //     $info['stock_acct_name'] = $item['stock_acct_id'] ? Db::name('account')->where('id',$item['stock_acct_id'])->value('true_name') : '';
        //     $info['goods_stall_id'] = $item['goods_stall_id'];
        //     $info['room'] = $item['room'];
        //     $rows[] = $info;
        // }
        // $data = [
        //     'rows'      => $rows,
        //     'total_page'=> ceil($total/$page_size),
        //     'page_size' => $page_size,
        //     'page'      => $page
        // ];
        // $this->success('成功','',$data);
    }
    public function add()
    {
        //品牌列表
        $brands = GoodsBrand::field(['id','name','first_letter'])->order('first_letter')->select();
        //商品种类列表
        $fields = ['id','type','name'];
        $categories = GoodsCategories::field($fields)->order('type')->select();
        foreach ($categories as $key => $row) {
            $categories[$key]['type'] = GoodsCategories::$types[$row['type']];
        }

        $this->assign([
            'brands'       => $brands,
            'categories'   => $categories,
            'size_sets'    => Goods::$size_sets,
        ]);

    	return view();
    }
    public function edit($id)
    {
        $goods = Db::name('goods')->where('id',$id)->find();
        $goods['picture'] = config('upload_path') . $goods['picture'];
        //品牌列表
        $brands = GoodsBrand::field(['id','name','first_letter'])->order('first_letter')->select();
        //商品种类列表
        $categories = GoodsCategories::field('id,type,name')->order('type')->select();
        foreach ($categories as $key => $row) {
            $categories[$key]['type'] = GoodsCategories::$types[$row['type']];
        }

        $this->assign([
            'goods'        => $goods,
            'brands'       => $brands,
            'categories'   => $categories,
            'size_sets'    => Goods::$size_sets,
        ]);
        return view();
    }
    protected function thumb($dir, $file_name)
    {
        $image = \think\Image::open("{$dir}{$file_name}");

        list($name, $ext) = explode('.', $file_name);
        $thumb_path = "{$dir}{$name}_tmb.{$ext}";
        
        if(file_exists($thumb_path)){
            echo 'exist<br>';
        } else {
            $image->thumb(80, 80)->save($thumb_path);
        }
    }
    public function doPic()
    {
        $page = max(input('page',0),1);
        $page_size = 50;

        $rows = Db::name('goods')->page($page, $page_size)->order('id DESC')->select();

        foreach ($rows as $row) {
            echo $row['id'] . '<br>';
            $parts = explode('/', $row['picture']);
            $file_name = array_pop($parts);
            $dir = dirname(ROOT_PATH) . config('upload_path') . implode('/', $parts);
            //echo $dir . '|' . $file_name;exit;
            $this->thumb($dir . '/', $file_name);
        }

    }
    // public function goodsHandle($id=0)
    // {
    //     //数据验证
    //     $data = input('post.');

    //     $validate = new Validate([
    //         ['cate_id','require','请选择类别'],
    //         ['brand_id','require','请选择品牌'],
    //         ['size_set','require','请选择尺码组']
    //     ]);
    //     if (!$validate->check($data)) {
    //         $this->error($validate->getError());
    //     }

    //     //上传文件
    //     $file = input('file.picture');  //文件太大获取为空
    //     //var_dump($file);
    //     if ($file) {
    //         $sub_path = date('ym') . '/' . date('d') .'/';
    //         $dir = dirname(ROOT_PATH) . config('upload_path') . $sub_path;
    //         $info = $file->rule('uniqid')->validate(['ext'=>'jpg,png','size'=>2*1024*1024])->move($dir);

    //         if (!$info) {
    //             $this->error($file->getError());
    //         } else {
    //             $file_name = $info->getSaveName();
    //             //缩略图
    //             $this->thumb($dir, $file_name);
    //             $data['picture'] = $sub_path . $file_name;
    //         }   
    //     } else {
    //         unset($data['picture']);    //有file字段??
    //     }
        
    //     //拼接商品名称
    //     $brand_name = GoodsBrand::where('id',$data['brand_id'])->value('name');
    //     $cate_name = GoodsCategories::where('id',$data['cate_id'])->value('name');
    //     $data['name'] = $brand_name . $cate_name;
        

    //     if ($id>0) {
    //         $acct_id = Goods::where('id',$id)->value('acct_id');
    //         if ($acct_id != Session::get('uid')) {
    //             $this->error('只能由添加者修改');
    //         }
    //         return Goods::update($data,['id'=>$id],true);
    //     } else {
    //         if (empty($data['picture'])) {
    //             $this->error('请上传文件');
    //         }
    //         $data['acct_id'] = Session::get('uid'); //添加者
    //         return Goods::add($data,true);
    //     }
    // }
    public function goodsHandle($id=0)
    {
        $id = $this->request->param('id');
        //数据验证
        $data = input('post.');

        $validate = new Validate([
            ['cate_id','require','请选择类别'],
            ['brand_id','require','请选择品牌'],
            ['size_set','require','请选择尺码组']
        ]);
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        //上传文件
        $files = input('file.picture');  //文件太大获取为空
        if($id>0){//编辑商品(单文件上传)
                if ($files) {
                $sub_path = date('ym') . '/' . date('d') .'/';
                $dir = dirname(ROOT_PATH) . config('upload_path') . $sub_path;
                $info = $files->rule('uniqid')->validate(['ext'=>'jpg,png','size'=>2*1024*1024])->move($dir);

                if (!$info) {
                    $this->error($files->getError());
                } else {
                    $file_name = $info->getSaveName();
                    //缩略图
                    $this->thumb($dir, $file_name);
                    $data['picture'] = $sub_path . $file_name;
                }   
            } else {
                unset($data['picture']);    //有file字段??
            }
            
            //拼接商品名称
            $brand_name = GoodsBrand::where('id',$data['brand_id'])->value('name');
            $cate_name = GoodsCategories::where('id',$data['cate_id'])->value('name');
            $data['name'] = $brand_name . $cate_name;
        

            $acct_id = Goods::where('id',$id)->value('acct_id');
            if ($acct_id != Session::get('uid')) {
                $this->error('只能由添加者修改');
            }
            return Goods::update($data,['id'=>$id],true);
        }else{//多文件上传
            if(!$files){
                $this->error('请上传文件');
            }
            foreach ($files as $file) {
                if ($file) {
                    $sub_path = date('ym') . '/' . date('d') .'/';
                    $dir = dirname(ROOT_PATH) . config('upload_path') . $sub_path;
                    $info = $file->rule('uniqid')->validate(['ext'=>'jpg,png','size'=>2*1024*1024])->move($dir);
        
                    if (!$info) {
                        $this->error($file->getError());
                    } else {
                        $file_name = $info->getSaveName();
                        //缩略图
                        $this->thumb($dir, $file_name);
                        $data['picture'] = $sub_path . $file_name;
                    }   
                } else {
                    unset($data['picture']);    //有file字段??
                }
                
                //拼接商品名称
                $brand_name = GoodsBrand::where('id',$data['brand_id'])->value('name');
                $cate_name = GoodsCategories::where('id',$data['cate_id'])->value('name');
                $data['name'] = $brand_name . $cate_name;
                
        
                if (empty($data['picture'])) {
                    $this->error('请上传文件');
                }
                $data['acct_id'] = Session::get('uid'); //添加者
                Goods::add($data,true);
            }
            $this->success('添加成功');
        }
        
        
    }
     //修改类别
     public function updataCate()
     {   
        $id = $this->request->param('id');
        $type = $this->request->param('type');
        $cate = GoodsCategories::where('id',$id)->update(['type'=>$type]);
        if(!empty($cate)){
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }
     }
    
    //商品类别
    public function cateList($name='')
    {   
        return view();
    }
    public function getCateList()
    {
        $where = [];
        $where = array_filter(input('post.'));
        if (!empty($where['name'])) {
            $where['name'] = ['like','%'.$where['name'].'%'];
        }
        
        $page = max(input('get.page',0),1);
        $page_size = 15;

        $total = Db::name('goods_categories')->where($where)->count();
        $rows = Db::name('goods_categories')->where($where)->page($page, $page_size)->order('add_time desc')->select();

        $types = GoodsCategories::$types;
        $units = GoodsCategories::$units;
        foreach ($rows as $key => $cate) {
            $rows[$key]['type'] = $types[$cate['type']];
            $rows[$key]['unit'] = $units[$cate['unit']];
            $rows[$key]['add_time'] = date('Y-m-d H:i',$cate['add_time']);
        }

        $data = [
            'rows'      => $rows,
            'total_page'=> ceil($total/$page_size),
            'page_size' => $page_size,
            'page'      => $page
        ];
        $this->success('成功','',$data);
    }
    public function cateHandle()
    {
        $data = input('post.');
        //数据验证
        $validate = new Validate([
            ['type','require','请选择类别'],
            ['name','require','名称必须'],
            ['unit','require','请选择单位'],
        ]);
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        $where = [
            'type'  => $data['type'],
            'name'  => $data['name'],
        ];
        if (Db::name('goods_categories')->where($where)->find()){
            $this->error('分类已存在');
        }
        $data['add_time'] = time();

        return GoodsCategories::add($data,true);
    }
    public function getCateListBySort()
    {
        $sort = input('post.sort_sel');
        if (empty($sort)) {
            $where['type'] = 1;
        } else {
            $where['type'] = array_search($sort ,GoodsCategories::$types);
        }

        $cates = Db::name('goods_categories')->where($where)->order('add_time desc')->select();
        $rows = [];

        foreach ($cates as $cate) {
            $row = [
                'id'    => $cate['id'],
                'val'   => $cate['name']
            ];
            $rows[] = $row;
        }
        $data = [
            'rows'      => $rows
        ];

        $this->success('成功','',$data);
    }
    /**
     * 清理过期商品（只保留一个月的商品）
     */
    public function clearGoods(){
        $time = time()-30*24*60*60;
        $res = Goods::where('add_time','<',$time)->delete();
        if(!empty($res)){
            $this->success('删除商品成功，只保留一个月的商品');
        }else{
            $this->error('没有过期的商品了');
        }
    }
}